package com.example.demo.file.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.entity.FileUpReturnEntity;
import com.example.demo.file.FileManager;
import com.example.demo.util.CommonUtil;
import com.example.demo.util.FileUtils;
import com.example.demo.util.PrimaryKeyUtil;
import com.example.demo.util.PropertiesUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LocalServerManager implements FileManager{
	private final String SAVETYPE = "0";
	
	final String PATH_SEPARATOR = "/";

	@Override
	public FileUpReturnEntity uploadSingleFile(MultipartFile file, String module, boolean dontChangeName,
			boolean dontCreateDateDir) throws Exception {
		
		String fileDir = PropertiesUtil.getProperty("localfile.path");
		
		fileDir = fileDir.endsWith(PATH_SEPARATOR)?fileDir:(fileDir + PATH_SEPARATOR);

		fileDir += module + PATH_SEPARATOR;
		String relativePath = module + PATH_SEPARATOR;
		
		String fileName = PrimaryKeyUtil.getUUIDWithOutLink() + FileUtils.getFileFormat(file.getOriginalFilename());
		if(!dontCreateDateDir) {
			String dateUrlPath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
			fileDir += dateUrlPath + PATH_SEPARATOR;
			relativePath += dateUrlPath + PATH_SEPARATOR;
		}
		
		if(dontChangeName) {
			fileName = file.getOriginalFilename();
		}
		
		String fileUrl = relativePath + fileName;
		
		log.info("文件保存路径>>>{},文件url>>>{}",(fileDir + fileName), fileUrl);
		
		File fileParentDir = new File(fileDir);
		
		if(!fileParentDir.exists()) {
			fileParentDir.mkdirs();
			log.info("文件夹已创建");
		}
		
		file.transferTo(new File(fileDir+fileName));
		
		log.info("上传文件到本地服务器完成");
		
		return new FileUpReturnEntity(fileUrl, SAVETYPE);
	}

	@Override
	public List<FileUpReturnEntity> uploadMultiFile(MultipartFile[] files, String module, boolean dontChangeName,
			boolean dontCreateDateDir) throws Exception {
		
		String fileDir = PropertiesUtil.getProperty("localfile.path");
		String fileUrlPrefix = PropertiesUtil.getProperty("localfile.prefix");
		
		fileDir = fileDir.endsWith(File.separator)?fileDir:(fileDir+File.separator);
		fileUrlPrefix = fileUrlPrefix.endsWith("/")?fileUrlPrefix:(fileUrlPrefix+"/");

		fileDir += module + File.separator;
		fileUrlPrefix += module + "/";
		
		
		if(!dontCreateDateDir) {
			String dateDir = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd").format(new Date());
			String dateUrlPath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
			fileDir += dateDir + File.separator;
			fileUrlPrefix += dateUrlPath + "/";
		}
		
		File fileParentDir = new File(fileDir);
		
		if(!fileParentDir.exists()) {
			fileParentDir.mkdirs();
			log.info("文件夹已创建");
		}
		
		int fileNum = files.length;
		
		List<FileUpReturnEntity> fileRetList = new ArrayList<>(fileNum);
		
		for (int i = 0; i < fileNum; i++) {
			MultipartFile file = files[i];
			
			String fileName = PrimaryKeyUtil.getUUIDWithOutLink() + FileUtils.getFileFormat(file.getOriginalFilename());
			
			if(dontChangeName) {
				fileName = file.getOriginalFilename();
			}
			
			String fileUrl = fileUrlPrefix + fileName;
			
			log.info("文件保存路径>>>{},文件url>>>{}",(fileDir+fileName),fileUrl);
			
			file.transferTo(new File(fileDir+fileName));
			
			fileRetList.add(new FileUpReturnEntity(fileUrl, SAVETYPE));
		}
		
		log.info("上传多文件到本地服务器完成");
		
		return fileRetList;
	}

	@Override
	public void readFileFromRequest(HttpServletResponse response, String fileUrl) throws Exception {
		// TODO Auto-generated method stub
		log.info("(本地文件服务器)文件访问路径为>>>{}",fileUrl);
		
		fileUrl = CommonUtil.encodeUrlCN(fileUrl);
		
		String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
		
		response.setContentType(CommonUtil.getContentType(fileName));
		response.setHeader("Content-disposition", "inline; filename=" + fileName);
		
		String fileDir = PropertiesUtil.getProperty("localfile.path");
		
		fileDir = fileDir.endsWith(File.separator)?fileDir:(fileDir+File.separator);
		
		String fileAbsolutePath = fileDir + fileUrl;
		
		InputStream fileStream = new FileInputStream(fileAbsolutePath);
		ServletOutputStream sos = response.getOutputStream();
		
		//读取文件流并返回给response
		IOUtils.copy(fileStream, sos);
		
        log.info("(本地文件服务器){}文件访问成功,已输出至响应中去",fileUrl);
        
        IOUtils.closeQuietly(sos);
        IOUtils.closeQuietly(fileStream);
        
        
        log.info("关闭连接");
	}

}
